﻿using System.ServiceModel.Web;
using Camelot.JSONAPI.Business;
using Camelot.JSONAPI.Models;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text.RegularExpressions;

namespace Camelot.JSONAPI
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class JsonService : IJsonService
    {
        public string Items(string command)
        {
            // Test if array or not
            var isCommandArray = Regex.IsMatch(command.Trim(), @"^\[.*?\]$");
            string jsonReturn = string.Empty;

            if (isCommandArray)
            {
                List<Command> commandObj = JsonConvert.DeserializeObject<List<Command>>(command);
                List<string> ret = commandObj.Select(ExecuteFactory.Execute).ToList();
                jsonReturn = string.Format("[{0}]", string.Join(",", ret.ToArray()));
            }
            else
            {
                Command commandObj = JsonConvert.DeserializeObject<Command>(command);
                jsonReturn = ExecuteFactory.Execute(commandObj);
            }

            return jsonReturn;
        }

        public string GetUser()
        {
            return WindowsIdentity.GetCurrent().Name;
        }
    }
}
